package com.sto.stoapp.activity.scanner;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.sto.stoapp.activity.R;
import com.sto.stoapp.dataprocess.ProcessScanCode;
import com.sto.stoapp.status.EnumScanCode;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.util.StringUtil;
import com.sto.stoapp.widget.StoHhmEditText;
import com.sto.stoapp.widget.StoHhmEditText.EditClickListener;
import com.sto.stoapp.widget.StoListenerActivity;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

@SuppressLint("HandlerLeak")
public class StoOnlineInquiryActivity extends StoListenerActivity {

	public static final String APP_KEY="baqiang";
	public static final String APP_SECRET="2ef025380b7c41f4bd6e705c92dfb49f";

	private TextView inquiryInfo;
	private StoHhmEditText code;



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.sto_online_inquiry);
		Bundle extras = getIntent().getExtras();

		this.setTitleBottom(R.string.online_inquiry_list,
				extras.getString("busiType"));

		initWidget();
		initListen();
	}

	// 初始化控件
	private void initWidget() {

		code = (StoHhmEditText) this.findViewById(R.id.online_inquiry_code);
		inquiryInfo = (TextView) this.findViewById(R.id.display_inquiry_info);
		initPointLayout(false);
		code.setHint("车签号可只输入后9位");
	}

	// 监听控件
	@SuppressLint("NewApi")
	private void initListen() {

		/*
		 * 修改小退功能
		 * 
		 * @modify mgf
		 * 
		 * @date 2014-03-18
		 */
		((StoHhmEditText) code).setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				onBackPressed();
			}

			@Override
			public void onEditClickListener(View v) {
				String str = code.getText().toString();
				if (str != null) {
					if (str.length() == 9 && StringUtil.isNumeric(str)) {
						code.setText("STO" + str);
					}
					onScanResults(code.getText().toString());
				}
			}
		});
	}



	@Override
	public void onBackPressed() {
		finish();
	}

	@Override
	protected void onDestroy() {
		// handler.removeMessages(MessageType.ONLINE_INQUIRY_TYPE);
		super.onDestroy();
	}

	@Override
	protected void handlerScanData(String str) {

		if (str != null && !str.equals("")) {
			String result = str;
			if (!result.equals("111111111111")) {
				EnumTableNames en = EnumTableNames.STATUS_TABLE_SCANNING_RECEIVE;
				if (result.startsWith("STO")) {
					en = EnumTableNames.STATUS_TABLE_LOADCAR_SENDPIECE;
				}
				EnumScanCode status = ProcessScanCode.getInstance(this)
						.ScanCodeResolve(result, en);
				code.setText("");
				code.setText(result);
				code.setSelection(code.length());
				switch (status) {
				// 条码空
				case CODE_EMPTY:
					Helper.showSoundToast(StoOnlineInquiryActivity.this,
							getString(R.string.code_empty), false);
					break;
				// 单号位数错误
	
				// 非法条码
				case CAR_SEAL_ILLEGAL:
				case CODE_ILLEGAL:
					Helper.showSoundToast(StoOnlineInquiryActivity.this,
							getString(R.string.error_code), false);
					break;
				// 成功条码
				case CODE_SEAL_OK:
				case CODE_WAY_BILL:
					dokuaijianleixingchaxun(result);
					break;
				default:
					break;
				}
			} else {
				Helper.showSoundToast(StoOnlineInquiryActivity.this,
						getString(R.string.online_inquiry_null), false);
			}
		}

	}
//http://222.66.109.133:22225/stosy_test/trackForXml.action?
	public void dokuaijianleixingchaxun(final String code) {

		String url="http://expressapi.sto-express.cn:8000/api/Track/GetScans?billcode=" +
				code+"&format=xml&sort=desc&AppKey="+APP_KEY+"&AppSecret="+APP_SECRET;

		Log.e("wj","查件url:"+url);


		RequestQueue queue = Volley.newRequestQueue(this);
		StringRequest stringRequest = new StringRequest(Method.GET,
				url,
				new Response.Listener<String>() {
					@Override
					public void onResponse(String response) {
						inquiryInfo.setText(parseXMLWithPull(response));
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						Log.e("TAG", error.getMessage(), error);
						Helper.showToast(StoOnlineInquiryActivity.this,
								error.getMessage());
					}
				}) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				Map<String, String> map = new HashMap<String, String>();
				map.put("billcode", code);
				return map;
			}
		};
		queue.add(stringRequest);
	}

	public String parserXml(String text) {
		String str = "";
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();

			Document document = db.parse(new ByteArrayInputStream(text
					.getBytes()));
			NodeList employees = document.getChildNodes();
			for (int i = 0; i < employees.getLength(); i++) {
				Node employee = employees.item(i);
				NodeList employeeInfo = employee.getChildNodes();
				for (int j = 0; j < employeeInfo.getLength(); j++) {
					Node node = employeeInfo.item(j);
					NodeList employeeMeta = node.getChildNodes();
					for (int k = 0; k < employeeMeta.getLength(); k++) {

						str = str
								+ employeeMeta.item(k).getTextContent() + "\n\n";
						// System.out.println(employeeMeta.item(k).getNodeName()
						// + ":" + employeeMeta.item(k).getTextContent());
					}
				}
			}
			System.out.println("解析完毕");
		} catch (FileNotFoundException e) {
			System.out.println(e.getMessage());
		} catch (ParserConfigurationException e) {
			System.out.println(e.getMessage());
		} catch (SAXException e) {
			System.out.println(e.getMessage());
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
		return str;
	}

	private String parseXMLWithPull(String xmlData){

		String str="";
		try {
			XmlPullParserFactory factory= XmlPullParserFactory.newInstance();
			XmlPullParser xmlPullParser=factory.newPullParser();
			xmlPullParser.setInput(new StringReader(xmlData));
			int eventType=xmlPullParser.getEventType();
			while (eventType!=XmlPullParser.END_DOCUMENT){
				String nodeName=xmlPullParser.getName();
				switch (eventType){
					case XmlPullParser.START_TAG:

						if("billcode".equals(nodeName)){
							str=str+"单号："+xmlPullParser.nextText()+"\n\n";
						}else if("time".equals(nodeName)){
							str=str+xmlPullParser.nextText()+"   ";
						}else if("scantype".equals(nodeName)){
							str=str+xmlPullParser.nextText()+"\n";
						}else if("memo".equals(nodeName)){
							str=str+xmlPullParser.nextText()+"\n\n";
						}

						break;
					case XmlPullParser.END_TAG:
						break;
				}

				eventType=xmlPullParser.next();
			}
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return str;
	}
}
